package cn.itsource.zcn.user.service.impl;

import cn.itsource.zcn.user.domain.Logininfo;
import cn.itsource.zcn.user.domain.User;
import cn.itsource.zcn.user.mapper.LogininfoMapper;
import cn.itsource.zcn.user.mapper.UserMapper;
import cn.itsource.zcn.user.service.IUserService;
import cn.itsource.zcn.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2021-08-19 17:18:43
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper tUserMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;


    /**
     * 新增数据
     *
     * @param tUser 实例对象
     */
    @Override
    @Transactional
    public void save(User tUser) {
        tUserMapper.save(tUser);
    }

    /**
     * 修改数据
     *
     * @param tUser 实例对象
     */
    @Override
    @Transactional
    public void update(User tUser) {
        tUserMapper.update(tUser);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     */
    @Override
    @Transactional
    public void delete(Long id) {
        tUserMapper.delete(id);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Long id) {
        return tUserMapper.queryById(id);
    }

    @Override
    public User queryByPhone(String phone) {
        return tUserMapper.queryByPhone(phone);
    }

    /**
     * 查询多条数据
     *
     * @return 对象列表
     */
    @Override
    public List<User> queryAll() {
        return tUserMapper.queryAll();
    }

    @Override
    public Logininfo login(Logininfo logininfo) {
        // 去数据库查询该用户是否存在
        Logininfo login = logininfoMapper.login(logininfo);
        if(login==null){
            throw new RuntimeException("用户名或密码错误");
        }
        // 密码加密处理再与之对比
        String salt = login.getSalt();
        String byMd5 = MD5Utils.encrypByMd5(logininfo.getPassword() + salt);
        if(!byMd5.equals(login.getPassword())){
            throw new RuntimeException("用户名或密码错误");
        }
        // 用户名和密码都正确
        return login;
    }


}
